package com.shycloud.mido.common.security.mobile;

import lombok.SneakyThrows;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;

import java.util.Collection;

/**
 * @author npc
 * @date 2018/1/9
 * 手机号登录令牌
 */
public class MobileAuthenticationToken extends AbstractAuthenticationToken {

	private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;

	private final Object principal;

	public MobileAuthenticationToken(String mobile) {
		super(null);
		this.principal = mobile;
		setAuthenticated(false);
	}

	public MobileAuthenticationToken(String mobile, String code) {
		super(null);
		if ("".equals(code) || code == null) {
			this.principal = mobile;
		} else {
			this.principal = mobile + "," + code;
		}
		setAuthenticated(false);
	}

	/**
	 * WX 登录切分
	 *
	 * @param wxCode
	 * @param code
	 * @param phone
	 * @author nianhua.jiang
	 * @date 2020/9/4 9:17
	 **/
	public MobileAuthenticationToken(String wxCode, String code, String phone) {
		super(null);
		this.principal = wxCode + ",wxCode,wxCode";
		setAuthenticated(false);
	}

	//小程序验证码登录
	public MobileAuthenticationToken(String username, String code, String phone, String xxxx) {
		super(null);
		this.principal = username + "," + code + ",miniCode,miniCode";
		setAuthenticated(false);
	}

	/**
	 * 小程序微信登陆 切分
	 *
	 * @return
	 * @author nianhua.jiang
	 * @date 2020/10/26 16:27
	 **/
	public MobileAuthenticationToken(String wxMiniCode, String ex1, String ex2, String ex3, String ex4) {
		super(null);
		this.principal = wxMiniCode + ",miniWxCode,miniWxCode,miniWxCode,miniWxCode";
		setAuthenticated(false);
	}


	public MobileAuthenticationToken(Object principal,
									 Collection<? extends GrantedAuthority> authorities) {
		super(authorities);
		this.principal = principal;
		super.setAuthenticated(true);
	}

	@Override
	public Object getPrincipal() {
		return this.principal;
	}

	@Override
	public Object getCredentials() {
		return null;
	}

	@Override
	@SneakyThrows
	public void setAuthenticated(boolean isAuthenticated) {
		if (isAuthenticated) {
			throw new IllegalArgumentException(
					"Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
		}

		super.setAuthenticated(false);
	}

	@Override
	public void eraseCredentials() {
		super.eraseCredentials();
	}
}
